package com.ruoyi.quartz.task;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.SysCheckIn;
import com.ruoyi.system.mapper.SysCheckInMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 老人在院状态定时任务
 * @author jinyao
 */
@Component("elderHospitalizedStatus")
public class ElderHospitalizedStatus {

    private static final Logger log = LoggerFactory.getLogger(ElderStatusTask.class);

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysCheckInMapper sysCheckInMapper;

    public void updateElderHospitalizedStatus() {
        log.debug("开始更新老人在院状态");
        Date now = new Date();
        //这里应该调用服务层的方法，更新老人在院状态
        SysUser sysUser = new SysUser();
        sysUser.setDelFlag("0");
        //查询所有老人
        List<SysUser> sysUsers = sysUserMapper.selectElderList(sysUser);
        //获取所有老人的id
        Set<Long> collect = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toSet());
        SysCheckIn sysCheckIn = new SysCheckIn();
        sysCheckIn.setDelFlag("0");
        sysCheckIn.setStatus("0");
        sysCheckIn.setAuditStatus("1");
        sysCheckIn.setElderUserIds(collect);
        List<SysCheckIn> sysCheckIns = sysCheckInMapper.selectSysCheckInList(sysCheckIn);
        if (sysCheckIns.isEmpty()){
            log.info("没有需要更新的老人");
            return;
        }
        //根据老人id分组
        Map<Long, List<SysCheckIn>> collect1 = sysCheckIns.stream().collect(Collectors.groupingBy(SysCheckIn::getElderUserId));
        for (SysUser s : sysUsers) {
            //先设定 不在院状态
            s.setInHospitalStatus("0");
            List<SysCheckIn> sysCheckIns1 = collect1.get(s.getUserId());
            if (sysCheckIns1!= null && !sysCheckIns1.isEmpty()) {
                for (SysCheckIn checkIn : sysCheckIns1) {
                    if (now.compareTo(checkIn.getCheckInTime()) >= 0 && now.compareTo(checkIn.getExpectedCheckOutTime()) <= 0) {
                        //在院状态
                        s.setInHospitalStatus("1");
                        break;
                    }
                }
            }
            sysUserMapper.updateUser(s);
        }
        log.debug("结束更新老人在院状态");
    }


}
